import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/user/Users'
import Rights from '../components/power/Rights'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home', component: Home, redirect: '/welcome', children: [
      { path: '/welcome', name: 'welcome', component: Welcome },
      { path: '/users', name: 'users', component: Users },
      { path: '/rights', name: 'rights', component: Rights },
    ]
  }
]

const router = new VueRouter({
  routes: routes,
  // mode: "history"
})

// 挂载路由全局守卫 to将要访问的路径 next是函数
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    if (sessionStorage.getItem('token')) {
      return next('/home')
    }
    return next();
  }
  if (!sessionStorage.getItem('token')) {
    return next('/login');
  }
  next();
})

export default router
